package com.pingan.common.util;

import org.apache.commons.lang.StringUtils;

public class UrlParser {

	public static String[] parse(String url) {
		String[] urlArray = new String[3];

		String result = StringUtils.remove(url, "\r");
		result = StringUtils.remove(result, "\n");
		result = StringUtils.remove(result, "\r\n");
		result = StringUtils.remove(result, "\'");
		result = StringUtils.remove(result, "\"");
		result = StringUtils.remove(result, "http://");

		String[] array = StringUtils.splitByWholeSeparatorPreserveAllTokens(
				result, "?");

		if (array != null && array.length >= 1) {
			if (array.length == 1) {
				urlArray[2] = "";
			} else {
				StringBuilder sb = new StringBuilder();
				for (int i = 1; i < array.length; i++) {
					if (i != array.length - 1) {
						sb.append(array[i]).append("?");
					} else {
						sb.append(array[i]);
					}
				}
				urlArray[2] = sb.toString();
			}

			String hostAndPath = array[0];

			String[] array1 = StringUtils
					.splitByWholeSeparatorPreserveAllTokens(hostAndPath, "/");

			if (array1 != null && array1.length >= 1) {
				if (array1.length == 1) {
					urlArray[0] = array1[0];
					urlArray[1] = "";
				} else {
					urlArray[0] = array1[0];
					StringBuilder sb1 = new StringBuilder();
					for (int i = 1; i < array1.length; i++) {
						if (i != array1.length - 1) {
							sb1.append(array1[i]).append("/");
						} else {
							sb1.append(array1[i]);
						}

					}
					urlArray[1] = sb1.toString();
				}
			} else {
				urlArray[0] = "";
				urlArray[1] = "";
			}

		} else {
			urlArray[0] = "";
			urlArray[1] = "";
			urlArray[2] = "";
		}

		if (!StringUtils.isBlank(urlArray[0])) {
			urlArray[0] = "http://" + urlArray[0];
		}
		return urlArray;
	}

	public static void main(String[] args) {
		String[] s = UrlParser.parse("www.tudou.com/asldf?atqwe=adfa");
		for (int i = 0; i < s.length; i++) {
			System.out.println(s[i]);
		}
	}
}
